package com.hcc.flow.server.advice;

import java.lang.reflect.Method;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.hcc.flow.server.annotation.Original;
import com.hcc.flow.server.common.model.ApiResult;
import com.hcc.flow.server.common.utils.ResultUtil;

/**
 * 请求响应处理类<br>
 * 
 * 对加了的方法的数据进行加密操作
 * 
 * @author 韩长长 
 * 
 * 
 *
 */
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {


	private static ThreadLocal<Boolean> encryptLocal = new ThreadLocal<Boolean>();

	public static void setEncryptStatus(boolean status) {
		encryptLocal.set(status);
	}

	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		return true;
	}

	@SuppressWarnings("unchecked")
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
		// 可以通过调用EncryptResponseBodyAdvice.setEncryptStatus(false);来动态设置不加密操作
		Boolean status = encryptLocal.get();
		if (status != null && status == false) {
			encryptLocal.remove();
			// 组装返回格式
			if (body instanceof ApiResult) {
				ApiResult<Object> result = (ApiResult<Object>) body;
				if (!result.getCode().equals("0")) {
					return result;
				}
			}
			return ResultUtil.success(body);
		}
		Method method = returnType.getMethod();
		// 组装返回格式
		if (body instanceof ApiResult) {
			ApiResult<Object> result = (ApiResult<Object>) body;
			return result;
		}
		// 判断是否是字节图片之类的返回类型
		if (body instanceof byte[]) {
			return body;
		}
		// 函数面加密注解Original
		if (method.isAnnotationPresent(Original.class)) {
			return body;
		}
		// 判断是否是swagger的请求，如果是，则不进行格式化转化,直接返回
		/*if (request.getURI().toString().contains("swagger") || request.getURI().toString().contains("v2/api-docs")) {
			return body;
		}
		*/
		return ResultUtil.success(body);
	}
}
